package com.seednia.module.core.xport;

import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.util.List;
import java.util.Map;

import com.seednia.foundation.framework.dto.AbstractRecord;
import com.seednia.foundation.framework.dto.QueryParams;
import com.seednia.foundation.framework.service.IDataOrientedService;
import com.seednia.foundation.framework.service.ServiceContainer;
import com.seednia.foundation.framework.service.ServiceException;

/**
 * This is the abstract base class for Exporter. All Exporters should extend this class
 * and implement the exportTo operation.
 * 
 * @author Young Suk Ahn
 *
 */
public abstract class AbstractExporter extends AbstractXporterBase implements IExporter {


	/**
	 * Exports the content of objToExport to the output stream os.
	 * @param objToExport contains the data to be exported
	 * @param os the output stream to be written the exported data.
	 * @param params any optional parameters if required for exporting
	 * @throws Exception
	 */
	public abstract void exportTo(XportDataContainer objToExport, OutputStream os, Map<String, Object> params) throws Exception;

	/**
	 * Default behavior is to create all data from 
	 */
	@Override
	public void exportAppData(String comments, OutputStream os, Map<String, Object> params) throws ServiceException, XportException 
	{
		List<IDataOrientedService> doServices = ServiceContainer.getInstance().getListByType(IDataOrientedService.class);
		
		XportDataContainer dataContainer = new XportDataContainer();
		dataContainer.setComments(comments);
		
		for (IDataOrientedService doService: doServices ) {
			List<AbstractRecord> records = doService.listRecords(null, null, new QueryParams(0, Integer.MAX_VALUE));
			
			XportData xportData = new XportData(doService.getId(), records);
			dataContainer.addXportData(xportData);
		}
		
		try {
			exportTo(dataContainer, os, params);
		} catch (Exception e) {
			throw new XportException(e);
		}
	}
	
	@Override
	public void exportAppData(String comments, File file, Map<String, Object> params) throws ServiceException, IOException, XportException {
		
		OutputStream os = new BufferedOutputStream(new FileOutputStream(file));
		exportAppData(comments, os, params);
		os.flush();
		os.close();		
	}


}
